package com.pojoin.cms.dao.impl.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.pojoin.cms.dao.RoleDao;
import com.pojoin.cms.domain.Role;
import com.pojoin.cms.domain.persistence.RolePersistence;
import com.pojoin.cms.util.criteria.Criteria;
import com.pojoin.cms.util.criteria.CriteriaOperator;
import com.pojoin.cms.util.criteria.impl.CriteriaKeyValue;
import com.pojoin.cms.util.criteria.orderby.Orderby;
import com.pojoin.cms.util.pager.Pager;
import com.pojoin.cms.util.pager.PagerChecker;

public class RoleDaoImpl extends BaseDaoHibernate<RolePersistence> implements RoleDao {

	private final String baseSql = "from RolePersistence ";
	@Override
	public Role addRole(Role role) {
		RolePersistence rp = this.convert(role);
		this.insertObject(rp);
		return rp;
	}

	private RolePersistence convert(Role role) {
		RolePersistence p = new RolePersistence();
		p.setDeleted(role.getDeleted());
		p.setRemark(role.getRemark());
		p.setRoleId(role.getRoleId());
		p.setRoleName(role.getRoleName());
		p.setRoleTitle(role.getRoleTitle());
		p.setUsers(role.getUsers());
		return p;
	}

	@Override
	public void delRole(Long roleId) {
		RolePersistence rp = this.getObjectById(roleId);
		this.deleteObject(rp);
	}

	@Override
	public List<Role> search(Criteria c, Orderby orderby, Pager pager) {
		pager = PagerChecker.checkPageer(pager);
		List<Role> roleList = new ArrayList<Role>();
		List<RolePersistence> list = this.queryPagerObjectListByCriteriaAndOrderby(c, orderby, pager.getPageNo(), pager.getPageSize());
		if(list != null){
			for(Role r : list){
				roleList.add(r);
			}
		}
		return roleList;
	}

	@Override
	public Role updateRole(Role role) {
		RolePersistence r = this.getObjectById(role.getRoleId());
//		r = this.convert(role);
		BeanUtils.copyProperties(role, r);
		return this.updateObject(r);
	}

	@Override
	String getBaseSql() {
		return this.baseSql;
	}

	@Override
	public List<Role> search(Criteria c, Orderby orderby) {
		List<Role> roleList = new ArrayList<Role>();
		List<RolePersistence> list = this.queryObjectListByCriter(c, orderby);
		if(list != null){
			for(Role r : list){
				roleList.add(r);
			}
		}
		return roleList;
	}

	@Override
	public Role findRoleById(long roleId) {
		return this.getObjectById(roleId);
	}

	@Override
	public boolean isExistRole(Role role) {
		Criteria c = new CriteriaKeyValue("roleName", CriteriaOperator.EQUALS, role.getRoleName());
		String hql = this.getBaseSql() + " where " + c.getSQLCriteria();
		return this.objectExist(hql);
	}

}
